<?php
if (0){
    echo '<form action="" method="post" enctype="multipart/form-data"><input name="filedata" type="file"><input type="submit"></form><br/>---------<br/>\n';
}

if (isset($_FILES['filedata'])){
    $file_type = isset($_GET['type']) ? $_GET['type'] : NULL;
    switch ($file_type){
        case "file":
            $allow_ext = array("zip", "rar", "txt");
            $file_size = 10000; // 10M
        break;
        case "img":
            $allow_ext = array("jpg", "jpeg", "gif", "png");
            $file_size = 1000; // 1M
        break;
        case "flash":
            $allow_ext = array("swf");
            $file_size = 5000; // 5M
        break;
        case "media":
            $allow_ext = array("avi", "mp4", "3gp");
            $file_size = 60000; // 60M
        break;
    }
    if (!isset($file_size)){
        echo json_encode(array("err" => "参数传递错误，请刷新页面重试！", "msg" => ""));
        die;
    }

    $file_path_info = pathinfo($_FILES['filedata']['name']);
    if (!in_array(strtolower($file_path_info['extension']), $allow_ext)){
        // 文件类型限制
        echo json_encode(array("err" => "文件类型限制！", "msg" => ""));
        die;
    }

    $tmp_file_size = $_FILES['filedata']['size'];
    if ($tmp_file_size > $file_size*1024){ // 设置上传文件大小上限为1M
        // 上传文件大小超限
        echo json_encode(array("err" => "上传文件大小超限！", "msg" => ""));
        die;
    }

    $file_dir = "upload_dire/" . date("Y/m/d");
    if (!(file_exists($file_dir) && is_dir($file_dir))){
        // 文件目录不存在，创建目录
        $dir_arr = explode("/", $file_dir);
        array_shift($dir_arr);
        $mk_dir = "upload_dire/";
        foreach ($dir_arr as $each_dir){
            $mk_dir .= $each_dir . "/";
            if (!file_exists($mk_dir)){
                mkdir($mk_dir, 0777);
            }
        }
    }

    $filename = $file_dir . "/" . $file_path_info['basename'];
    if (file_exists($filename)){
        $filename = $file_dir . "/" . $file_path_info['basename'] . "-" . date("His_") . mt_rand(10, 99) . "." . $file_path_info['extension'];
    }
    @move_uploaded_file($_FILES['filedata']['tmp_name'], $filename); // 转移上传文件
    $file_url = "!http://blog.rickyxu.info/" . $filename;
    //针对xheditor：若返回的地址最前面为半角的感叹号：“!”，表示为立即上传模式，上传成功后不需要点“确定”按钮，随后自动插入到编辑器内容中。
	echo json_encode(array("err" => "", "msg" => $file_url));
}else{
    // 上传文件参数错误
    echo json_encode(array("err" => "上传文件失败！", "msg" => ""));
    die;
}
?>